/*
 * BrowseUpload.java
 * Activity for user to select picture, create story and add tags for uploading.
 */
package edu.ntu.mobilestomp;

import android.app.TabActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TabHost;
import edu.ntu.helper.RestClient;
import edu.ntu.helper.RestClient.RequestMethod;
import edu.ntu.helper.UploadTask;

public class BrowseUpload extends TabActivity implements OnClickListener {
	private static final int SELECT_PICTURE = 1;
	private String galleryImagePath;
	private String fileManagerPath;
	private String filePath;
	private ImageView iv;
	private EditText etTitle;
	private EditText etDetails;
	private EditText etTag1;
	private EditText etTag2;
	private EditText etTag3;
	private Button uploadButton;

	private Bitmap bm;

	private BitmapFactory.Options options = new BitmapFactory.Options();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Create Tab layout
		TabHost tabHost = getTabHost();

		LayoutInflater.from(this).inflate(R.layout.uploadtabs,
				tabHost.getTabContentView(), true);

		tabHost.addTab(tabHost.newTabSpec("picTab").setIndicator("Picture")
				.setContent(R.id.pictureView));
		tabHost.addTab(tabHost.newTabSpec("storyTab").setIndicator("Story")
				.setContent(R.id.storyView));
		tabHost.addTab(tabHost.newTabSpec("tagsTab").setIndicator("Tags")
				.setContent(R.id.tagsView));

		iv = (ImageView) findViewById(R.id.picture);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			// Picture taken with Camera
			filePath = extras.getString("pic_path");
			options.inSampleSize = 4;
			bm = BitmapFactory.decodeFile(filePath, options);
		} else {
			// Setting default image
			bm = BitmapFactory.decodeResource(getResources(),
					R.drawable.android_touch);
		}

		iv.setImageBitmap(bm);

		// Set listener to image
		iv.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				Log.v("TEST", "TOUCHED IMAGE");
				// in onCreate or any event where your want the user to
				// select a file
				Intent intent = new Intent();
				intent.setType("image/*");
				intent.setAction(Intent.ACTION_GET_CONTENT);
				startActivityForResult(
						Intent.createChooser(intent, "Select Picture"),
						SELECT_PICTURE);

				return false;
			}
		});

		etTitle = (EditText) findViewById(R.id.title);
		etDetails = (EditText) findViewById(R.id.details);
		etTag1 = (EditText) findViewById(R.id.tag1);
		etTag2 = (EditText) findViewById(R.id.tag2);
		etTag3 = (EditText) findViewById(R.id.tag3);
		uploadButton = (Button) findViewById(R.id.uploadButton);

		uploadButton.setOnClickListener(this);
		if (filePath == null) {
			uploadButton.setEnabled(false);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		if (filePath == null) {
			MenuItem item = menu.findItem(R.id.uploadOption);
			item.setEnabled(false);
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		// Add record option selected
		case R.id.uploadOption:
			doAddNewRecord();
			break;

		}
		return true;
	}

	public void doAddNewRecord() {
		String filename;
		String tags;

		String[] items;
		items = filePath.split("/");

		filename = items[items.length - 1];
		// Phrasing tags
		tags = etTag1.getText().toString() + "," + etTag2.getText().toString()
				+ "," + etTag3.getText().toString();

		// Upload picture into server
		new UploadTask(getApplicationContext()).execute(filePath);

		// Setting logs
		Log.v("TITLE", filename);
		Log.v("TITLE", etTitle.getText().toString());
		Log.v("TITLE", etDetails.getText().toString());
		Log.v("TITLE", tags);

		// Insert record into server
		doInsertRecord(filename, etTitle.getText().toString(), etDetails
				.getText().toString(), tags);
		
		this.finish();

	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();

				fileManagerPath = selectedImageUri.getPath();
				galleryImagePath = getPath(selectedImageUri);

				if (galleryImagePath != null) {
					filePath = galleryImagePath;
				} else {
					filePath = fileManagerPath;

				}

				bm = BitmapFactory.decodeFile(filePath, options);
				iv.setImageBitmap(null);
				iv.setImageBitmap(bm);

				uploadButton.setEnabled(true);

			}
		}
	}

	// Function to return Image Path
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		if (cursor != null) {
			int column_index = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} else
			return null;
	}

	// Function to call Server Web service for inserting new records
	private void doInsertRecord(String aLink, String aTitle, String aDetails,
			String aTags) {
		//Set REST client
		RestClient client = new RestClient(getString(R.string.base_url)
				+ "/add_new_record.php");

		// Set Parameters
		client.AddParam("alink", aLink);
		client.AddParam("atitle", aTitle);
		client.AddParam("adetails", aDetails);
		client.AddParam("atags", aTags);
		try {
			client.Execute(RequestMethod.POST);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Submit HTTP
		String response = client.getResponse();
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		Log.v("DEBUG CLICK", v.toString());
		doAddNewRecord();

	}

}
